'use strict';

const db = uniCloud.database()
const postsCollection = db.collection('posts')

exports.main = async (event, context) => {
	try {
		const { page = 1, pageSize = 10, keyword = '' } = event
		
		// 构建查询条件
		const query = {}
		if (keyword) {
			query.title = new RegExp(keyword, 'i')
		}
		
		// 获取总数
		const countResult = await postsCollection.where(query).count()
		const total = countResult.total
		
		// 获取分页数据
		const list = await postsCollection
			.where(query)
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.orderBy('createTime', 'desc')
			.get()
		
		// 获取用户信息
		const userIds = list.data.map(item => item.userId)
		const users = await db.collection('users')
			.where({
				_id: db.command.in(userIds)
			})
			.get()
		
		// 合并用户信息
		const userMap = {}
		users.data.forEach(user => {
			userMap[user._id] = {
				avatar: user.avatar,
				nickname: user.nickname
			}
		})
		
		const posts = list.data.map(post => {
			return {
				...post,
				userInfo: userMap[post.userId] || {
					avatar: '',
					nickname: '未知用户'
				}
			}
		})
		
		return {
			code: 0,
			msg: '获取成功',
			data: {
				list: posts,
				total
			}
		}
	} catch (error) {
		console.error('获取帖子列表失败', error)
		return {
			code: -1,
			msg: '获取失败',
			data: null
		}
	}
} 